import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import sun.misc.BASE64Encoder;
import sun.misc.CharacterEncoder;

/**
 * This is the class that controls logging in a user
 */
public class Login {

	/**
	 * This method checks the login credentials of a user
	 * 
	 * @params username the user's username
	 * @params password the user's password
	 * @return true, if user can log in successfully
	 */
	public static boolean loginUser(String username, String password) {
		// See if the user is in the database
		PasswordHash encrypted_pass = generatePasswordHash(password);
		String qry = "SELECT * FROM Users WHERE username = " + "'" + username
				+ "'" + "AND password = " + "'" + encrypted_pass + "'";
		ResultSet rs = Database.selectQuery(qry);
		// check if user is in database
		if (rs.first()) {
			// check if user is suspended
			if (rs.getBoolean("suspended"))
			{
				return false;
			}
			else
			{
				return true;
			}
		}
		else
		{
			return false;
		}
	}

	/**
	 * Returns the user with the given username
	 * 
	 * @return the user with the given username, or null if none exists
	 */
	public static User getUser(String username) {
		String qry = "SELECT * FROM Users WHERE username = " + "'" + username
				+ "'";
		ResultSet rs = Database.selectQuery(qry);
		String foundEncryptedPass;
		int foundAccessLevel;
		boolean foundSuspendState;
		User myUser;
		try {
			while (rs.next()) {
				foundEncryptedPass = rs.getString("encrypted_password");
				foundAccessLevel = rs.getInt("access_level");
				foundSuspendState = rs.getBoolean("suspended");
			}
		} catch (Exception e) {
			myUser = new User();
			myUser.setPasswordHash(new PasswordHash(foundEncryptedPass));
			myUser.setAccessLevel(foundAccessLevel);
			myUser.setName(Name.readName(username));
			myUser.setSuspendState(foundSuspendState);
		}
		return myUser;
	}

	/**
	 * This method encrypts the user's submitted password
	 * 
	 * @param password
	 *            the submitted password
	 * @return the new PasswordHash containing the encrypted password
	 */
	public static PasswordHash generatePasswordHash(String password) {
		return new PasswordHash(encrypt(password));
	}

	/**
	 * Returns an encrypted password key corresponding to the given input
	 * 
	 * @param password
	 *            the unencrypted password
	 * @return the encrypted password
	 */
	public static String encrypt(String password) {
		return password;
	}

	/**
	 * This method changes the suspend state of the user
	 * 
	 * @param user
	 *            the user to be edited
	 * @param newState
	 *            the new suspend state
	 * @return the old suspend state
	 */
	public static boolean changeUserSuspendState(User user, boolean newState) {
		boolean b = user.isSuspended();
		user.setSuspendState(newState);
		return b;
	}
}
